package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.model.WebSite;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.RequestScopeObjectService;
import com.m3958.firstgwt.server.service.SiteConfiger;
import com.m3958.firstgwt.server.service.SiteConfiger.SiteConfigerKeyName;
import com.m3958.firstgwt.server.session.SessionUser;
import com.m3958.firstgwt.server.types.AppConstants;

import freemarker.template.TemplateException;

@Singleton
public class StaticFileServlet  extends HttpServlet {
		  /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	@Inject
	private AppUtilService autils;
	
	@Inject
	private Injector injector;
	
	@Inject
	private SiteConfiger siteConfiger;
	

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) 
	                               throws ServletException, IOException {
	    
		String uri = req.getRequestURI();
		RequestScopeObjectService rso = injector.getInstance(RequestScopeObjectService.class);
		if("/in".equals(uri) || "/FirstGwt.html".equals(uri)){
		    Locale ul = req.getLocale();
		    System.out.println(ul.getLanguage() + "_" + ul.getCountry());
			SessionUser su = injector.getInstance(SessionUser.class);
			boolean inDebug = req.getRequestURL().toString().contains(":8888");
			if(!su.isLogined()){
				if(inDebug){
//					res.sendRedirect("/login.html#next=sitebuilder&debug=true");
					res.sendRedirect("/login?next=sitebuilder&debug=true");
				}else{
//					res.sendRedirect("http://" + rso.getRequestHostName() + "/login.html#next=sitebuilder");
					res.sendRedirect("http://" + rso.getRequestHostName() + "/login?next=sitebuilder");
				}
				return;
			}
			if(inDebug){
				sendTpl(req, res,"FirstGwt.ftl");
			}else{
				sendTpl(req, res,"FirstGwt.ftl");
			}
			return;
		}
		
		
		File f = getNoneFtlFile(rso,req);
		if(f == null){
		    String file = req.getPathTranslated();
		    f = new File(file);
		    if (!f.isFile()) {
		    	//如果url不是特定的開頭，就此結束。
		    	redirectToWebFront(req, res);
		    	return;
		    }
		}
	    autils.sendSiteFile(req,res,f,getServletContext().getMimeType(f.getAbsolutePath()));
	  }
	
	private void redirectToWebFront(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException{
    	RequestDispatcher rd = req.getRequestDispatcher("/webfront");
    	req.setAttribute("origin_ruri", req.getRequestURI());
    	rd.forward(req, res);
	}
	
	
	private File getNoneFtlFile(RequestScopeObjectService rso,HttpServletRequest req){
		String uri = req.getRequestURI();
		WebSite ws = rso.getRequestWebSite();
		if(ws == null)return null;
		if(uri.toLowerCase().endsWith(ws.getTplTech()))return null;//限制直接访问模板
		File ttr = new File(new File(siteConfiger.getValue(SiteConfigerKeyName.SITE_ROOT), ws.getId()+""),rso.getRequestWebHost().getTheme());
		File f = new File(ttr,uri);
		String tplp = req.getParameter(AppConstants.TPL_PARAMETER_NAME);
		if("/".equals(uri) && tplp != null && !tplp.isEmpty()){
			File df = new File(ttr,"/index.html");
			if(df.exists())return df;
			df = new File(ttr,"/index.htm");
			if(df.exists())return df;
			df = new File(ttr,"/default.html");
			if(df.exists())return df;
			df = new File(ttr,"/default.htm");
			if(df.exists())return df;
		}
		if(f.exists() && f.isFile()){
			return f;
		}
		return null;
	}
	
	private void sendTpl(HttpServletRequest req, HttpServletResponse res,String fn){
		res.setContentType("text/html;charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		try {
			autils.sendWebContextTpl(req, res, fn);
		} catch (IOException e) {
			if(e instanceof FileNotFoundException){
				try {
					autils.sendWebContextTpl(req, res, "FirstGwt.html");
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (TemplateException e1) {
					e1.printStackTrace();
				}
			}else{
				e.printStackTrace();
			}
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
	

}
